package com.dalei.vdserver.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.dalei.vdserver.model.Log;

public class LogDaoImpl extends JdbcDaoSupport implements LogDao {

	@Override
	public int saveLog(final Log log) {
		// TODO Auto-generated method stub
		final String sql = "INSERT INTO vds_log VALUES (?, ?, ?, ?, ?, ?, ?)";
		int rowAffected = 0;
		try {
			getJdbcTemplate().update(sql, new PreparedStatementSetter() {

				@Override
				public void setValues(PreparedStatement ps) throws SQLException {
					// TODO Auto-generated method stub
					ps.setInt(1, log.getFid());
					ps.setInt(2, log.getVehicleInformationId());
					ps.setInt(3, log.getDeviceId());
					ps.setInt(4, log.getUserId());
					ps.setInt(5, log.getOdometerReading());
					ps.setString(6, log.getNotes());
					Date date = log.getTimeStamp();
					Timestamp timestamp = new Timestamp(date.getTime());
					ps.setTimestamp(7, timestamp);
				}
			});
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return -1;
		}
		return rowAffected;
	}

	@Override
	public int clearLog(int fid) {
		// TODO Auto-generated method stub
		final String sql = "DELETE FROM vds_log WHERE _fid=?";
		int rowAffected = 0;
		try {
			rowAffected = getJdbcTemplate().update(sql, new Object[] { fid });
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return -1;
		}
		return rowAffected;
	}
}
